<template>
  <a-drawer
    :width="520"
    :title="typeMap[operateType]"
    :placement="placement"
    :visible="visible"
    @close="visible = false"
  >
    <template #extra>
      <a-space :size="8">
        <a-button @click="visible = false" v-if="operateType != 'view'">
          <template #icon>
            <i class="s-icon iconfont icon-cancel" />
          </template>
          {{ t("base.cancel") }}
        </a-button>
        <a-button
          class="s-button"
          :loading="okLoading"
          type="primary"
          :disabled="disabled"
          @click="onFinish"
        >
          <template #icon>
            <i
              class="s-icon iconfont icon-tubiao_tijiao"
              style="height: auto"
            />
          </template>
          {{ operateType === "view" ? t("base.ok") : t("base.save") }}
        </a-button>
      </a-space>
    </template>
    <template v-slot:default>
      <a-form
        ref="formValidate"
        :model="formInline"
        layout="vertical"
        labelAlign="right"
        autocomplete="off"
      >
        <s-title>{{ t("base.baseInfo") }}</s-title>
        <a-form-item
          :label="t('sysRole6')"
          name="name"
          :rules="[{ required: true, message: '请输入角色名称!' }]"
        >
          <a-input
            v-if="operateType != 'view'"
            v-model:value="formInline.name"
            v-input.trim.textFilter
            :placeholder="t('placeholder149')"
          />
          <div v-else>{{ formInline.name }}</div>
        </a-form-item>

        <a-form-item
          :label="t('sysRole7')"
          name="slug"
          :rules="[{ required: true, message: t('placeholder150') }]"
        >
          <a-input
            v-if="operateType != 'view'"
            v-model:value="formInline.slug"
            :placeholder="t('placeholder150')"
            v-input.trim.textFilter
          />
          <div v-else>{{ formInline.slug }}</div>
        </a-form-item>

        <a-form-item :label="t('sysRole8')" name="desc">
          <a-textarea
            v-if="operateType != 'view'"
            v-model:value="formInline.desc"
            v-input.textFilter
            :placeholder="t('placeholder151')"
            :rows="3"
            :maxlength="100"
            showCount
          />
          <div v-else>{{ formInline.desc }}</div>
        </a-form-item>

        <s-title> {{ t("base.rolePower") }}</s-title>
        <a-row>
          <a-col :offset="0" :span="24">
            <a-space direction="vertical" :size="16">
              <a-checkbox
                v-if="operateType != 'view'"
                @change="onChange"
                style="margin-left: 24px"
                v-model:checked="checkedAll"
                >{{ t("sysRole11") }}</a-checkbox
              >
              <a-tree
                :multiple="true"
                v-model:checkedKeys="formInline.permission_ids"
                :checkable="true"
                :checkStrictly="false"
                :defaultExpandAll="false"
                :tree-data="powerOptions"
                :field-names="{
                  children: 'children',
                  title: 'label',
                  key: 'value',
                }"
                :height="undefined"
                @check="onCheck"
                :disabled="operateType === 'view'"
              />
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </template>
  </a-drawer>
</template>

<script lang="ts">
import { DrawerProps } from "ant-design-vue";
import { getTreeDataOptionsId } from "../../utils";
import {
  formInline,
  operateType,
  powerOptions,
  tmpArray,
  checkedAll,
  set_formInline,
  parentArray,
  visible,
} from "../../store";
let permission_ids: any = [];
export default defineComponent({
  setup(props, { emit, expose }) {
    const formValidate = ref<any>(null);
    const okLoading = ref(false);
    const placement = ref<DrawerProps["placement"]>("right");
    const typeMap = reactive<any>({
      edit: getProxyT("sysRole12"),
      add: getProxyT("sysRole13"),
      view: getProxyT("sysRole14"),
    });
    const disabled = computed(
      () => isEmptyType(formInline.name) || isEmptyType(formInline.slug)
    );
    const showDrawer = async (type: string, record?: any) =>
      set_formInline(type, formInline, record);
    expose({ showDrawer });
    const onClose = () => {
      const routeStore = useRouteStore();
      routeStore?.fetchMenuList();
      okLoading.value = false;
      visible.value = false;
    };
    const onFinish = async () => {
      try {
        let res = reactive<any>(null);
        switch (operateType.value) {
          case "view":
            visible.value = false;
            break;
          case "add":
            okLoading.value = true;
            res = await roleApi.create({
              name: formInline.name,
              slug: formInline.slug,
              permission_ids: [
                ...new Set([...formInline.permission_ids, ...permission_ids]),
              ]?.join?.(","),
              desc: formInline.desc,
            });
            if (res.code != 200) {
              okLoading.value = false;
              return message.error(res.message);
            }
            onClose();
            emit("refreshTable");
            message.success($t("base.addSuccess"));
            break;
          case "edit":
            okLoading.value = true;
            res = await roleApi.update({
              id: formInline.id,
              name: formInline.name,
              slug: formInline.slug,
              permission_ids: [
                ...new Set([
                  ...formInline.permission_ids,
                  ...permission_ids,
                  ...parentArray.value,
                ]),
              ]?.join?.(","),
              desc: formInline.desc,
            });
            if (res.code != 200) return message.error(res.message);
            onClose();
            emit("fetchList");
            message.success($t("base.updateSucess"));
            break;
        }
      } catch (error: any) {
        message.error(error.message);
      } finally {
        okLoading.value = false;
      }
    };
    watch(
      () => visible.value,
      (newState) => {
        if (newState === false) {
          formValidate.value.clearValidate();
          clearObjAttr(formInline);
        }
      }
    );

    const onChange = ({ target: { checked } }: any) => {
      if (checked === true) {
        tmpArray.value = [];
        formInline.permission_ids = getTreeDataOptionsId(powerOptions.value);
      }
      if (checked === false) formInline.permission_ids = [];
    };
    const onCheck = (checkedKeys: any, e: any) => {
      tmpArray.value = [];
      permission_ids = [
        ...new Set([...formInline.permission_ids, ...e.halfCheckedKeys]),
      ];
      checkedAll.value =
        formInline.permission_ids.length ===
        getTreeDataOptionsId(powerOptions.value).length;
      parentArray.value = checkedKeys;
    };

    return {
      t: $t,
      onCheck,
      onChange,
      checkedAll,
      disabled,
      formValidate,
      onFinish,
      placement,
      visible,
      okLoading,
      typeMap,
      operateType,
      showDrawer,
      formInline,
      powerOptions: powerOptions,
    };
  },
});
</script>
